package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.VisitDto;
import com.zzyl.entity.Visit;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.VisitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

@Service
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 新增预约
     *
     * @param visitDto
     */
    @Override
    public void addReservation(VisitDto visitDto) {
        Visit visit = BeanUtil.toBean(visitDto, Visit.class);

        //判断当前手机号是否预约改时间段
        VisitVo visitVo = reservationMapper.isTimeAlreadyReservatedByPhone(visit.getTime(), visit.getMobile());
        if (ObjectUtil.isNotEmpty(visitVo)) {
            throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
        }

        visit.setStatus(0);
        reservationMapper.insertReservation(visit);
    }

    /**
     * 查询每个时间段剩余预约次数
     *
     * @param time
     * @return
     */
    @Override
    public List<Map<String, Object>> countReservationByTime(Long time) {
        DateTime startTime = new DateTime(time);
        DateTime endTime = new DateTime(time + 24 * 60 * 60 * 1000 - 1000);
        return reservationMapper.countReservationByTime(startTime, endTime);
    }

    /**
     * 分页查询预约
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResponse<VisitVo> pageReservations(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Page<VisitVo> page = reservationMapper.pageReservations(status, UserThreadLocal.getUserId());
        return PageResponse.of(page, VisitVo.class);
    }

    /**
     * 取消预约
     *
     * @param id
     */
    @Override
    public void updateReservationStatus(Long id) {
        Long userId = UserThreadLocal.getUserId();
        reservationMapper.updateReservationStatus(id,userId);
    }

    /**
     * 查询当天取消预约数量
     *
     * @return
     */
    @Override
    public Integer countCancelReservation() {
        //获取当前登录用户id
        Long userId = UserThreadLocal.getUserId();
        //获取当天时间
        LocalDate time = LocalDate.now();
        return reservationMapper.countCancelReservation(userId,time);
    }
}
